package com.jielin.handling.service.material.impl;

import com.jielin.handling.entity.auditresult.AuditResult;
import com.jielin.handling.entity.material.*;
import com.jielin.handling.entity.police.PoliceMan;
import com.jielin.handling.entity.record.RecordDetailedVideo;
import com.jielin.handling.entity.unit.Organization;
import com.jielin.handling.exception.ResultEnum;
import com.jielin.handling.mapper.auditrecorder.AuditRecoderMapper;
import com.jielin.handling.mapper.material.MaterialFileMapper;
import com.jielin.handling.mapper.material.MaterialModelMapper;
import com.jielin.handling.mapper.material.MaterialTypeDocumentMapper;
import com.jielin.handling.mapper.material.MaterialTypeMapper;
import com.jielin.handling.mapper.police.PoliceCaseMapper;
import com.jielin.handling.mapper.police.PoliceManMapper;
import com.jielin.handling.mapper.record.RecordDetailedMapper;
import com.jielin.handling.mapper.tsuspect.TSuspecMapper;
import com.jielin.handling.mapper.unit.UnitMapper;
import com.jielin.handling.service.material.MaterialTypeService;
import com.jielin.handling.service.xsky.XskyService;
import com.jielin.handling.util.*;
import com.jielin.handling.util.pdfutil.PdfUtil;
import lombok.extern.slf4j.Slf4j;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Service
@Slf4j
public class MaterialTypeServiceImpl implements MaterialTypeService {
    @Autowired
    private MaterialTypeMapper maTypeMapper;
    @Autowired
    private MaterialModelMapper maModelMapper;
    @Autowired
    TSuspecMapper tSuspecMapper;
    @Autowired
    AuditRecoderMapper auditRecoderMapper;
    @Autowired
    private PoliceManMapper policeManMapper;
    @Autowired
    private PoliceCaseMapper policeCaseMapper;
    @Autowired
    private UnitMapper unitMapper;
    @Autowired
    private MaterialTypeDocumentMapper maTypeDocumentMapper;
    @Autowired
    private MaterialFileMapper mfMapper;
    @Autowired
    private RecordDetailedMapper recordDetailedMapper;
    @Autowired
    private XskyService xskyService;

    /**
     * 保证卷宗唯一生成
     */
    public volatile static List<String> onlyOneMaterialTypeList = new CopyOnWriteArrayList<>();

    @Override
    public List<MaterialType> findMaterialByAllAndName(String caseCode, String policeId, String caseSuspectId,
                                                       String materialTypeName, int isRetract) {
        if (StringUtil.isEmpty(caseCode) || StringUtil.isEmpty(policeId) || StringUtil.isEmpty(caseSuspectId)) {
            return null;
        }
        return maTypeMapper.findMaterialByCaseCodeEx(caseCode, caseSuspectId, policeId, isRetract, materialTypeName);
    }

    @Override
    public MaterialType findById(String materialtypeid) {
        return maTypeMapper.findById(materialtypeid);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public List<MaterialType> findMeaterialmodel(String caseCode, String caseName, String policeId,
                                                 String caseSuspectId, int isRetract) {
        if (StringUtil.isEmpty(caseCode) || StringUtil.isEmpty(policeId) || StringUtil.isEmpty(caseSuspectId)) {
            return null;
        }
        if (StringUtil.isEmpty(caseName)) {
            caseName = policeCaseMapper.findCaseNameByCaseCode(caseCode);
            if (StringUtil.isEmpty(caseName)) {
                log.error("根据案件编号查询案件名称为空");
                return null;
            }
        }
        String onlyOneMaterialTypeString = caseCode + policeId + caseSuspectId + isRetract;
        if (onlyOneMaterialTypeList.contains(onlyOneMaterialTypeString)) {
            log.error("卷宗在生成，请稍等...");
            return null;
        }

        List<MaterialType> mtList = maTypeMapper.findMaterialByCaseCode(caseCode, caseSuspectId, policeId, isRetract);
        List<MaterialTypeDocument> mtdList = null;// 审讯视频文件夹
        List<MaterialFile> mfList = null;// 审讯录像视频
        Date now = new Date();
        if (mtList.size() == 0) { // 如果查询到的一级目录为空，就从模板信息表复制添加一级目录 /caseSuspectId TODO 根据单位编号查询对应的一级标准目录
            // 添加到生成卷宗列表
            onlyOneMaterialTypeList.add(onlyOneMaterialTypeString);

            List<MaterialModel> mmlist = maModelMapper.findAllModel(1);// 获取标准模板
            log.info("......MaterialTypeServiceImpl==>findMeaterialmodel:获取标准模板添加到对应的案件");
            mtdList = new ArrayList<>();
            mfList = new ArrayList<>();
            MaterialType mt = null;
            for (MaterialModel materialModel : mmlist) {

                mt = new MaterialType();
                mt.setId(StringUtil.generatorUUID());
                mt.setCasecode(caseCode);
                mt.setCasename(caseName);
                mt.setFiletype(materialModel.getFiletype());
                mt.setUploadpoliceid(policeId);
                mt.setMaterialtypename(materialModel.getMaterialname());
                mt.setCasesuspectid(caseSuspectId);
                String suspecName = tSuspecMapper.selectNameById(caseSuspectId);
                mt.setCaseSuspectName(StringUtil.isEmpty(suspecName) ? "无" : suspecName);
                mt.setImgPath(materialModel.getImgPath());
                mt.setCreateDate(now);
                mt.setModifyDate(now);
//				maTypeMapper.addMaterialType(mt);// 初始化模板
                mtList.add(mt);

                // 创建一级文件夹存放路径==》 案件名称-警员id-案件编号/嫌疑人姓名/一级目录名称
                // jdk1.8的join方法与下面拼接一样的效果
                /*
                 * {@code String message = String.join("-", "Java", "is", "cool"); // message
                 * returned is: "Java-is-cool" }
                 */
//				String teString = String.join("-", mt.getCasename(), mt.getUploadpoliceid(), mt.getCasecode())
//						+ String.join(File.separator, "", mt.getCaseSuspectName(), mt.getMaterialtypename());
                String rootpath = mt.getCasename() + "-" + mt.getUploadpoliceid() + "-" + mt.getCasecode()
                        + File.separator + mt.getCaseSuspectName() + File.separator + mt.getMaterialtypename();

                // 设置存放图片文件的路径
                String path = ConstantUtil.FILE_PATH + rootpath;
                File newFile = new File(path);
                if (!newFile.exists()) {
                    newFile.mkdirs();
                }

                String thumbnailpath = ConstantUtil.FILE_PATH + rootpath + File.separator;// 存放位置

                int tmpNum = 0;
                // 将审讯视频加入卷宗材料
                if ("办案区视频".equals(mt.getMaterialtypename())) {
                    MaterialTypeDocument mtd = new MaterialTypeDocument();// 文件夹
                    mtd.setId(StringUtil.generatorUUID());
                    mtd.setDocumentname("办案区录像");
                    mtd.setMaterialtypeid(mt.getId());
                    mtd.setCreateDate(now);
                    mtd.setModifyDate(now);

                    thumbnailpath += (mtd.getDocumentname() + File.separator);
                    File newFile1 = new File(thumbnailpath);
                    if (!newFile1.exists()) {
                        newFile1.mkdirs();
                    }

                    // 获取录像文件
                    List<String> rdlist = recordDetailedMapper.findVideoBySuspectId(caseSuspectId);
                    if (rdlist.size() > 0) {
                        MaterialFile mFile = null;
                        for (String videoPaths : rdlist) {
                            if (!StringUtil.isEmpty(videoPaths)) {
                                String[] videoPathArray = videoPaths.split(",");
                                for (String videoPath : videoPathArray) {
                                    if (!StringUtil.isEmpty(videoPath)) {
                                        try {
//											String fileName = videoPath.substring(videoPath.lastIndexOf("/") + 1,
                                            String fileName = videoPath.substring(
                                                    videoPath.lastIndexOf(File.separator) + 1,
                                                    videoPath.lastIndexOf("."));
                                            String fileType = videoPath.substring(videoPath.lastIndexOf("."),
                                                    videoPath.length());
                                            mFile = new MaterialFile();
                                            mFile.setId(StringUtil.generatorUUID());
                                            mFile.setMaterialtypedocumentid(mtd.getId());
                                            mFile.setFilename(fileName);
                                            mFile.setFiletype(fileType);
                                            mFile.setUrl(videoPath);
                                            mFile.setCreateDate(now);
                                            mFile.setModifyDate(now);

                                            // 生成视频缩略图
                                            String truepath = VideoImageUtil.randomGrabberFFmpegImage(videoPath,
                                                    VideoImageUtil.MOD);
                                            // 设置缩略图路径
                                            mFile.setThumbnailpath(truepath);

                                            String allFileName = videoPath.substring(
                                                    videoPath.lastIndexOf(File.separator) + 1, videoPath.length());
                                            // 复制文件到电子卷宗目录下
                                            FileUtil.copyFile(new File(videoPath),
                                                    new File(thumbnailpath + allFileName));
                                            String thumbFileName = truepath.substring(
                                                    truepath.lastIndexOf(File.separator) + 1, truepath.length());
                                            FileUtil.copyFile(new File(truepath),
                                                    new File(thumbnailpath + thumbFileName));
                                            log.info("复制文件到电子卷宗目录下成功！原路径:" + videoPath + "电子卷宗路径:" + thumbnailpath
                                                    + fileName);
                                            log.info("复制文件到电子卷宗目录下成功！原路径:" + truepath + "电子卷宗路径:" + thumbnailpath
                                                    + thumbFileName);
                                            mfList.add(mFile);
                                            tmpNum++;
                                        } catch (org.bytedeco.javacv.FrameGrabber.Exception e) {
                                            log.error("生成视频缩略图报错", e);
                                            continue;
                                        } catch (IOException e) {
                                            log.error("复制视频文件到卷宗目录下报错", e);
                                            continue;
                                        } catch (Exception e) {
                                            log.error("videoPath{},截取路径报错：", videoPath, e);
                                            continue;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    mtd.setCount(tmpNum);// 设置文件夹下的文件数量
                    mtdList.add(mtd);
                    mt.setCount(1);// 设置一级目录数量
                } else if ("诉讼文书卷".equals(mt.getMaterialtypename())) {// 将笔录pdf文件加入卷宗材料
                    MaterialTypeDocument mtd = new MaterialTypeDocument();// 文件夹
                    mtd.setId(StringUtil.generatorUUID());
                    mtd.setDocumentname("笔录文件夹");
                    mtd.setMaterialtypeid(mt.getId());
                    mtd.setCreateDate(now);
                    mtd.setModifyDate(now);

                    thumbnailpath += (mtd.getDocumentname() + File.separator);
                    File newFile1 = new File(thumbnailpath);
                    if (!newFile1.exists()) {
                        newFile1.mkdirs();
                    }

                    // 获取pdf笔录文件
                    List<String> rdlist = recordDetailedMapper.findPdfBySuspectId(caseSuspectId);
                    if (rdlist.size() > 0) {
                        MaterialFile mFile = null;
                        for (String pdfPath : rdlist) {
                            try {
//											String fileName = pdfPath.substring(pdfPath.lastIndexOf("/") + 1,
                                String fileName = pdfPath.substring(pdfPath.lastIndexOf(File.separator) + 1,
                                        pdfPath.lastIndexOf("."));
                                String fileType = pdfPath.substring(pdfPath.lastIndexOf("."), pdfPath.length());
                                mFile = new MaterialFile();
                                mFile.setId(StringUtil.generatorUUID());
                                mFile.setMaterialtypedocumentid(mtd.getId());
                                mFile.setFilename(fileName);
                                mFile.setFiletype(fileType);
                                mFile.setUrl(pdfPath);
                                mFile.setCreateDate(now);
                                mFile.setModifyDate(now);

//								String thumbnailpath = ConstantUtil.FILE_PATH + rootpath + File.separator;// 缩略图的存放位置
//								String thumbnailtruePath = thumbnailpath + fileName + "thumbnail" + ".jpg";
//								File newFile1 = new File(thumbnailpath);
//								if (!newFile1.exists()) {
//									newFile1.mkdirs();
//								}
                                // 生成pdf缩略图
                                String thumbnailtruePath = PdfUtil.tranfer(pdfPath, 1);
                                // 设置缩略图路径
                                mFile.setThumbnailpath(thumbnailtruePath);

                                String allFileName = pdfPath.substring(pdfPath.lastIndexOf(File.separator) + 1,
                                        pdfPath.length());
                                // 复制文件到电子卷宗目录下
                                FileUtil.copyFile(new File(pdfPath), new File(thumbnailpath + allFileName));
                                String thumbFileName = thumbnailtruePath.substring(
                                        thumbnailtruePath.lastIndexOf(File.separator) + 1, thumbnailtruePath.length());
                                FileUtil.copyFile(new File(thumbnailtruePath), new File(thumbnailpath + thumbFileName));
                                log.info("复制文件到电子卷宗目录下成功！原路径:" + pdfPath + "电子卷宗路径:" + thumbnailpath + fileName);
                                log.info("复制文件到电子卷宗目录下成功！原路径:" + thumbnailtruePath + "电子卷宗路径:" + thumbnailpath
                                        + thumbFileName);

                                mfList.add(mFile);
                                tmpNum++;
                            } catch (InterruptedException e) {
                                log.error("生成pdf缩略图报错", e);
                                continue;
                            } catch (IOException e) {
                                log.error("生成pdf缩略图报错||复制文件到电子卷宗目录下报错", e);
                                continue;
                            } catch (PDFSecurityException e) {
                                log.error("生成pdf缩略图报错", e);
                                continue;
                            } catch (PDFException e) {
                                log.error("生成pdf缩略图报错", e);
                                continue;
                            } catch (Exception e) {
                                log.error("pdfPath{},截取路径报错：", pdfPath, e);
                                continue;
                            }
                        }
                    }
                    mtd.setCount(tmpNum);// 设置文件夹下的文件数量
                    mtdList.add(mtd);
                    mt.setCount(1);// 设置一级目录数量
                }
            }
            try {
                // 1.初始化一级
                if (mtList.size() > 0) {
                    maTypeMapper.addMaterialTypes(mtList);
                }
                // 2.初始化审讯视频文件夹
                if (mtdList.size() > 0) {
                    maTypeDocumentMapper.addDocuments(mtdList);
                }
                // 3.添加审讯录像文件到审讯视频文件夹
                if (mfList.size() > 0) {
                    mfMapper.addFiles(mfList);
                }
            } catch (Exception e) {
                log.info("添加电子卷宗事务回滚:{}", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

            try {
                AuditResult ar = new AuditResult();
                ar.setId(StringUtil.generatorUUID());
                ar.setCaseCode(caseCode);
                ar.setCaseName(caseName);
                ar.setPoliceId(policeId);
                ar.setSuspectId(caseSuspectId);
                PoliceMan pm = policeManMapper.findpolicmanById(policeId);
                ar.setPoliceCode(StringUtil.isEmpty(pm.getPoliceCode()) ? "" : pm.getPoliceCode());
                ar.setPoliceName(StringUtil.isEmpty(pm.getName()) ? "" : pm.getName());
                if (!StringUtil.isEmpty(pm.getOrganizationid())) {
                    Organization o = unitMapper.findUnitInfoById(pm.getOrganizationid());
                    ar.setHandleUnitCode(StringUtil.isEmpty(o.getHandleUnitCode()) ? "" : o.getHandleUnitCode());
                }
                auditRecoderMapper.insertAudit(ar);// 添加记录到审核结果表里面
            } catch (Exception e) {
                log.info("添加记录到审核结果表事务回滚:{}", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

            // 移除出生成卷宗列表
            onlyOneMaterialTypeList.remove(onlyOneMaterialTypeString);
        }
        return mtList;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public List<Node> findMeaterialTree(String caseCode, String caseName, String policeId, String caseSuspectId,
                                        int isRetract) {
        if (StringUtil.isEmpty(caseCode) || StringUtil.isEmpty(policeId) || StringUtil.isEmpty(caseSuspectId)) {
            return null;
        }
        List<Node> listTree = new ArrayList<Node>();
        List<MaterialType> list = maTypeMapper.findMaterialByCaseCode(caseCode, caseSuspectId, policeId, isRetract);
//		if (list.size() == 0) { // 如果查询到的一级目录为空，就从模板信息表复制添加一级目录 // TODO 根据单位编号查询对应的一级标准目录
//			List<MaterialModel> mmlist = maModelMapper.findAllModel(1);// 获取标准模板
//			MaterialType mt = null;
//			list = new ArrayList<>();
//			for (MaterialModel materialModel : mmlist) {
//				mt = new MaterialType();
//				mt.setId(StringUtil.generatorUUID());
//				mt.setCasecode(caseCode);
//				mt.setCasename(caseName);
//				mt.setFiletype(materialModel.getFiletype());
//				mt.setUploadpoliceid(policeId);
//				mt.setMaterialtypename(materialModel.getMaterialname());
//				mt.setCasesuspectid(caseSuspectId);
//				mt.setCaseSuspectName(tSuspecMapper.selectById(caseSuspectId).getName());
//				maTypeMapper.addMaterialType(mt);// 初始化模板
//				list.add(mt);
//
//				// 创建一级文件夹存放路径==》 案件名称-警员id-案件编号/嫌疑人姓名/一级目录名称
//				String rootpath = mt.getCasename() + "-" + mt.getUploadpoliceid() + "-" + mt.getCasecode()
//						+ File.separator + mt.getCaseSuspectName() + File.separator + mt.getMaterialtypename();
//
//				// 设置存放图片文件的路径
//				String path = ConstantUtil.FILE_PATH + rootpath;
//				File newFile = new File(path);
//				if (!newFile.exists()) {
//					newFile.mkdirs();
//				}
//			}
//			AuditResult ar = new AuditResult();
//			ar.setId(StringUtil.generatorUUID());
//			ar.setCaseCode(caseCode);
//			ar.setCaseName(caseName);
//			ar.setPoliceId(policeId);
//			ar.setSuspectId(caseSuspectId);
//			PoliceMan pm = policeManMapper.findpolicmanById(policeId);
//			ar.setPoliceCode(StringUtil.isEmpty(pm.getPoliceCode()) ? "" : pm.getPoliceCode());
//			ar.setPoliceName(StringUtil.isEmpty(pm.getName()) ? "" : pm.getName());
//			if (!StringUtil.isEmpty(pm.getOrganizationid())) {
//				Organization o = unitMapper.findUnitInfoById(pm.getOrganizationid());
//				ar.setHandleUnitCode(StringUtil.isEmpty(o.getHandleUnitCode()) ? "" : o.getHandleUnitCode());
//			}
//			auditRecoderMapper.insertAudit(ar);
//		} else {
        Node nd = null;
        for (MaterialType materialType : list) {
            nd = new Node();
            nd.setId(materialType.getId());
            nd.setParentId(materialType.getFiletype());
            nd.setText(materialType.getMaterialtypename());
            listTree.add(nd);
        }

//		}
        return listTree;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public List<MaterialType> findMeaterialmodel2(String caseCode, String caseName, String policeId, String caseSuspectId, int isRetract) {
        if (StringUtil.isEmpty(caseName)) {
            caseName = policeCaseMapper.findCaseNameByCaseCode(caseCode);
            if (StringUtil.isEmpty(caseName)) {
                log.error("根据案件编号查询案件名称为空");
                return null;
            }
        }
        String onlyOneMaterialTypeString = caseCode + policeId + caseSuspectId + isRetract;
        if (onlyOneMaterialTypeList.contains(onlyOneMaterialTypeString)) {
            log.error("卷宗在生成，请稍等...");
            return null;
        }

        List<MaterialType> mtList = maTypeMapper.findMaterialByCaseCode(caseCode, caseSuspectId, policeId, isRetract);
        // 审讯视频文件夹
        List<MaterialTypeDocument> mtdList;
        // 审讯录像视频
        List<MaterialFile> mfList;
        // 修改路径后的审讯录像视频文件信息
        List<RecordDetailedVideo> rdvCopyList;
        Date now = new Date();
        // 如果查询到的一级目录为空，就从模板信息表复制添加一级目录 /caseSuspectId TODO 根据单位编号查询对应的一级标准目录
        if (CollectionUtils.isEmpty(mtList)) {
            // 添加到生成卷宗列表
            onlyOneMaterialTypeList.add(onlyOneMaterialTypeString);

            List<MaterialModel> mmlist = maModelMapper.findAllModel(1);
            log.info("......MaterialTypeServiceImpl==>findMeaterialmodel:获取标准模板添加到对应的案件");
            mtdList = new ArrayList<>();
            mfList = new ArrayList<>();
            rdvCopyList = new ArrayList<>();
            MaterialType mt;
            String suspecName = tSuspecMapper.selectNameById(caseSuspectId);
            for (MaterialModel materialModel : mmlist) {
                mt = MaterialType.builder().id(StringUtil.generatorUUID()).casecode(caseCode)
                        .casename(caseName).filetype(materialModel.getFiletype()).uploadpoliceid(policeId)
                        .materialtypename(materialModel.getMaterialname()).casesuspectid(caseSuspectId)
                        .caseSuspectName(StringUtil.isEmpty(suspecName) ? "无" : suspecName)
                        .imgPath(materialModel.getImgPath()).createDate(now).modifyDate(now).build();
                mtList.add(mt);

                // 创建一级文件夹存放路径==》 案件名称-警员id-案件编号/嫌疑人姓名/一级目录名称
                // jdk1.8的join方法与下面拼接一样的效果
                /*
                 * {@code String message = String.join("-", "Java", "is", "cool"); // message
                 * returned is: "Java-is-cool" }
                 */
//				String teString = String.join("-", mt.getCasename(), mt.getUploadpoliceid(), mt.getCasecode())
//						+ String.join(File.separator, "", mt.getCaseSuspectName(), mt.getMaterialtypename());
                String rootpath = mt.getCasename() + "-" + mt.getUploadpoliceid() + "-" + mt.getCasecode()
                        + File.separator + mt.getCaseSuspectName() + File.separator + mt.getMaterialtypename();

                // 文件夹存放位置
                String thumbnailpath = ConstantUtil.FILE_PATH + rootpath + File.separator;

                // 当前路径
                String thisPath;

                try {
                    // 兼容win
                    thumbnailpath = thumbnailpath.replace("\\", "/");
                    xskyService.uploadObject(ConstantUtil.XSKY_BUCKET_DOSSIER, thumbnailpath, "");
                } catch (Exception e) {
                    throw new RuntimeException(ResultEnum.XSKYUPLOADFAIL.getMsg(), e);
                }

                int tmpNum = 0;
                // 将审讯视频加入卷宗材料
                if ("办案区视频".equals(mt.getMaterialtypename())) {
                    // 文件夹
                    MaterialTypeDocument mtd = MaterialTypeDocument.builder().id(StringUtil.generatorUUID())
                            .documentname("办案区录像").materialtypeid(mt.getId()).createDate(now).modifyDate(now).build();

                    thumbnailpath += (mtd.getDocumentname() + File.separator);

                    // 获取录像文件
                    List<RecordDetailedVideo> rdvlist = recordDetailedMapper.findVideoBySuspectId2(caseSuspectId);
                    if (!CollectionUtils.isEmpty(rdvlist)) {
                        for (RecordDetailedVideo rdv : rdvlist) {
                            String videoPath = rdv.getWatermarkPlayPosition();
                            String videoThumbPath = rdv.getWatermarkThumb();
                            MaterialFile mFile;
                            try {
                                String fileName = videoPath.substring(videoPath.lastIndexOf("/") + 1,
//                                    String fileName = videoPath.substring(videoPath.lastIndexOf(File.separator) + 1,
                                        videoPath.lastIndexOf("."));
                                String fileType = videoPath.substring(videoPath.lastIndexOf("."));
                                mFile = MaterialFile.builder().id(StringUtil.generatorUUID())
                                        .materialtypedocumentid(mtd.getId()).filename(fileName)
                                        .filetype(fileType).createDate(now).modifyDate(now).build();

                                try {
                                    thisPath = thumbnailpath + fileName + fileType;
                                    // 兼容win
                                    thisPath = thisPath.replace("\\", "/");
                                    xskyService.uploadObjectThrows(ConstantUtil.XSKY_BUCKET_DOSSIER, thisPath, new File(videoPath));
                                    mFile.setUrl(ConstantUtil.XSKY_PREPATH_URL + thisPath);
                                } catch (Exception e) {
                                    throw new RuntimeException(ResultEnum.XSKYUPLOADFAIL.getMsg(), e);
                                }

                                try {
                                    thisPath = thumbnailpath + videoThumbPath.substring(
//                                            truepath.lastIndexOf(File.separator) + 1);
                                            videoThumbPath.lastIndexOf("/") + 1);
                                    // 兼容win
                                    thisPath = thisPath.replace("\\", "/");
                                    xskyService.uploadObjectThrows(ConstantUtil.XSKY_BUCKET_DOSSIER, thisPath, new File(videoThumbPath));
                                    // 设置缩略图路径
                                    mFile.setThumbnailpath(ConstantUtil.XSKY_PREPATH_URL + thisPath);
                                } catch (Exception e) {
                                    throw new RuntimeException(ResultEnum.XSKYUPLOADFAIL.getMsg(), e);
                                }

                                mfList.add(mFile);
                                tmpNum++;
                                rdvCopyList.add(RecordDetailedVideo.builder().id(rdv.getId())
                                        .videoPath(mFile.getUrl())
                                        .thumburl(mFile.getThumbnailpath())
                                        .watermarkVideoPath(mFile.getUrl())
                                        .watermarkThumburl(mFile.getThumbnailpath())
                                        .build());
                            } catch (Exception e) {
                                throw new RuntimeException("截取路径报错：videoPath=" + videoPath, e);
                            }
                            // 删除存储的录像文件
                            new Thread(() -> {
                                ZipUtil.deleteFile(new File(rdv.getWatermarkPlayPosition()));
                                ZipUtil.deleteFile(new File(rdv.getWatermarkThumb()));
                                ZipUtil.deleteFile(new File(rdv.getPlayPosition()));
                                ZipUtil.deleteFile(new File(rdv.getThumb()));
                            }).start();
                        }
                    }
                    // 设置文件夹下的文件数量
                    mtd.setCount(tmpNum);
                    mtdList.add(mtd);
                    // 设置一级目录数量
                    mt.setCount(1);
                    // 将笔录pdf文件加入卷宗材料
                } else if ("诉讼文书卷".equals(mt.getMaterialtypename())) {
                    // 文件夹
                    MaterialTypeDocument mtd = MaterialTypeDocument.builder().id(StringUtil.generatorUUID())
                            .documentname("笔录文件夹").materialtypeid(mt.getId()).createDate(now).modifyDate(now).build();

                    thumbnailpath += (mtd.getDocumentname() + File.separator);

                    // 获取pdf笔录文件
                    List<String> rdlist = recordDetailedMapper.findPdfBySuspectId(caseSuspectId);
                    if (!CollectionUtils.isEmpty(rdlist)) {
                        MaterialFile mFile = null;
                        for (String pdfPath : rdlist) {
                            try {
                                String fileName = pdfPath.substring(pdfPath.lastIndexOf("/") + 1,
//                                String fileName = pdfPath.substring(pdfPath.lastIndexOf(File.separator) + 1,
                                        pdfPath.lastIndexOf("."));
                                String fileType = pdfPath.substring(pdfPath.lastIndexOf("."), pdfPath.length());
                                mFile = MaterialFile.builder().id(StringUtil.generatorUUID())
                                        .materialtypedocumentid(mtd.getId()).filename(fileName)
                                        .filetype(fileType).createDate(now).modifyDate(now).build();

                                try {
                                    thisPath = thumbnailpath + fileName + fileType;
                                    // 兼容win
                                    thisPath = thisPath.replace("\\", "/");
                                    xskyService.uploadObjectThrows(ConstantUtil.XSKY_BUCKET_DOSSIER, thisPath, new File(pdfPath));
                                    mFile.setUrl(ConstantUtil.XSKY_PREPATH_URL + thisPath);
                                } catch (Exception e) {
                                    throw new RuntimeException(ResultEnum.XSKYUPLOADFAIL.getMsg(), e);
                                }

                                // 生成pdf缩略图
                                String thumbnailtruePath = PdfUtil.tranfer(pdfPath, 1);

                                try {
                                    thisPath = thumbnailpath + thumbnailtruePath.substring(
//                                            thumbnailtruePath.lastIndexOf(File.separator) + 1);
                                            thumbnailtruePath.lastIndexOf("/") + 1);
                                    // 兼容win
                                    thisPath = thisPath.replace("\\", "/");
                                    xskyService.uploadObjectThrows(ConstantUtil.XSKY_BUCKET_DOSSIER, thisPath, new File(thumbnailtruePath));
                                    // 设置缩略图路径
                                    mFile.setThumbnailpath(ConstantUtil.XSKY_PREPATH_URL + thisPath);
                                } catch (Exception e) {
                                    throw new RuntimeException(ResultEnum.XSKYUPLOADFAIL.getMsg(), e);
                                }

                                mfList.add(mFile);
                                tmpNum++;

                                // 删除存储的笔录文件
                                new Thread(() -> {
                                    ZipUtil.deleteFile(new File(pdfPath));
                                    ZipUtil.deleteFile(new File(thumbnailtruePath));
                                }).start();

                            } catch (InterruptedException e) {
                                log.error("生成pdf缩略图报错", e);
                                continue;
                            } catch (IOException e) {
                                log.error("生成pdf缩略图报错||复制文件到电子卷宗目录下报错", e);
                                continue;
                            } catch (PDFSecurityException e) {
                                log.error("生成pdf缩略图报错", e);
                                continue;
                            } catch (PDFException e) {
                                log.error("生成pdf缩略图报错", e);
                                continue;
                            } catch (Exception e) {
                                log.error("pdfPath{},截取路径报错：", pdfPath, e);
                                continue;
                            }
                        }

                    }
                    // 设置文件夹下的文件数量
                    mtd.setCount(tmpNum);
                    mtdList.add(mtd);
                    // 设置一级目录数量
                    mt.setCount(1);
                }
            }
            try {
                // 1.初始化一级
                if (!CollectionUtils.isEmpty(mtList)) {
                    maTypeMapper.addMaterialTypes(mtList);
                }
                // 2.初始化审讯视频文件夹
                if (!CollectionUtils.isEmpty(mtdList)) {
                    maTypeDocumentMapper.addDocuments(mtdList);
                }
                // 3.添加审讯录像文件到审讯视频文件夹
                if (!CollectionUtils.isEmpty(mfList)) {
                    mfMapper.addFiles(mfList);
                }
                // 4.更新办案区视频存储路径
                if(!CollectionUtils.isEmpty(rdvCopyList)){
                    recordDetailedMapper.updateDetailedVideo(rdvCopyList);
                }
            } catch (Exception e) {
                log.info("添加电子卷宗事务回滚:{}", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

            try {
                AuditResult ar = new AuditResult();
                ar.setId(StringUtil.generatorUUID());
                ar.setCaseCode(caseCode);
                ar.setCaseName(caseName);
                ar.setPoliceId(policeId);
                ar.setSuspectId(caseSuspectId);
                PoliceMan pm = policeManMapper.findpolicmanById(policeId);
                ar.setPoliceCode(StringUtil.isEmpty(pm.getPoliceCode()) ? "" : pm.getPoliceCode());
                ar.setPoliceName(StringUtil.isEmpty(pm.getName()) ? "" : pm.getName());
                if (!StringUtil.isEmpty(pm.getOrganizationid())) {
                    Organization o = unitMapper.findUnitInfoById(pm.getOrganizationid());
                    ar.setHandleUnitCode(StringUtil.isEmpty(o.getHandleUnitCode()) ? "" : o.getHandleUnitCode());
                }
                // 添加记录到审核结果表里面
                auditRecoderMapper.insertAudit(ar);
            } catch (Exception e) {
                log.info("添加记录到审核结果表事务回滚:{}", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

            // 移除出生成卷宗列表
            onlyOneMaterialTypeList.remove(onlyOneMaterialTypeString);
        }
        return mtList;
    }

}
